package logic

import (
	"web_app/dao/mysql"
	"web_app/dao/redis"
	"web_app/models"
	"web_app/pkg/snowflake"
)

// CreatePost 添加帖子详情
func CreatePost(post *models.Post) error {
	post.ID = snowflake.GenID()
	err := mysql.InsertPostModel(post)
	err = redis.CreatePost(post)
	return err
}

//根据id获取帖子详情
func GetPostDetailByID(id int64) (*models.ApiPostDetail, error) {
	return mysql.GetPostDetailByID(id)
}

//获取帖子列表
func GetPostList(page *models.Page) ([]*models.ApiPostDetail, error) {
	return mysql.GetPostList(page)
}

// VoteForPost 帖子投票功能
func VoteForPost(voteData *models.ParamsVoteData) error {
	return redis.VoteForPost(voteData)
}

func GetPostListInOrder(p *models.ParamsPostInOrder) (data []*models.ApiPostDetail, err error) {
	//1.去redis中获取ids
	var ids = make([]string, 0)
	ids, err = redis.GetPostListByOrder(p)
	if err != nil || len(ids) == 0 {
		return
	}
	//2.查询每条帖子的投票数
	voteData := make([]int64, 0, len(ids))
	voteData, err = redis.GetPostVoteData(ids)
	//3.根据ids获取postList
	data, err = mysql.GetPostListByIDs(ids)
	for i := 0; i < len(data); i++ {
		data[i].VoteNum = voteData[i]
	}
	return
}
